package com.blast.manager.net

import android.content.Intent
import android.text.TextUtils
import android.view.KeyEvent
import android.view.View
import android.view.ViewTreeObserver
import com.blast.manager.R
import com.blast.manager.blast.BlastActivity
import com.blast.manager.net.presenter.*
import com.blast.manager.net.ui.DetonatorListActivity
import com.wxl.common.AppContext
import com.wxl.common.base.AbsActivity
import com.wxl.common.life.ViewModelQuick
import com.wxl.common.room.entity.LeiGuanDelayEntity
import com.wxl.common.room.entity.LeiGuanEntity
import com.wxl.common.room.entity.LogEntity
import com.wxl.common.room.helper.DBHelper
import com.wxl.common.serialport.SerialPortManager
import com.wxl.common.util.ObservableUtil
import com.wxl.common.util.Screen
import com.wxl.common.util.Toll
import io.reactivex.ObservableOnSubscribe
import kotlinx.android.synthetic.main.activity_net_check_layout.*


/**
 * 组网
 */
class NetCheckActivity : AbsActivity() {

    var clickTime = 0L
    var isBlastIntent = false

    override fun getCreateContentViewId(): Int {
        return R.layout.activity_net_check_layout
    }

    override fun onCreateViewChanged() {
        isCheckAppUpgrade = false
        setTopTitle("组网检查")
        changeContentHeight()
        ViewModelQuick.observer(
            this,
            NetCheckChargePresenter::class.java,
            netCheckChargeText,
            netCheckElectricText
        )
        ViewModelQuick.observer(this, NetCheckPortPresenter::class.java, this)
        observer(NetCheckReadyPresenter::class.java)
        observer(NetCheckErrorPresenter::class.java)
        observer(NetCheckNumberPresenter::class.java)
        setOnClickEvent()
        show(NetCheckReadyPresenter::class.java,false)
    }


    private fun changeContentHeight(){
        netCheckChargeLayout.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener{
            override fun onGlobalLayout() {
                netCheckChargeLayout.viewTreeObserver.removeOnGlobalLayoutListener(this)
                netCheckParentLayout.layoutParams.height = Screen.getHeight(netCheckParentLayout.context) - netCheckChargeLayout.layoutParams.height - netCheckBtnLayout.layoutParams.height
            }
        })
    }

    private fun <P : AbsNetCheckPresenter> observer(cls: Class<P>) {
        ViewModelQuick.observer(this, cls, netCheckParentLayout)
    }

    fun <P : AbsNetCheckPresenter> show(cls: Class<P>, vararg args: Any) {
        ViewModelQuick.get(this, cls).show(*args)
    }

    fun showText(isFailed:Boolean,text: String) {
        if(isFailed) {
            showOnlyBack()
        }
        show(NetCheckNumberPresenter::class.java, text)
    }

    override fun onKeyDownEvent(keyCode: Int, event: KeyEvent?): Boolean {
        if (keyCode == KeyEvent.KEYCODE_F1) {
            ViewModelQuick.get(this, NetCheckErrorPresenter::class.java)
                .onKeyDownEvent(keyCode, event)
            netCheckBackBtn.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_F2) {
            netCheckChargeBtn1.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_F3) {
            netCheckChargeBtn2.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_F4) {
            ViewModelQuick.get(this, NetCheckErrorPresenter::class.java)
                .onKeyDownEvent(keyCode, event)
            netCheckLookBtn.performClick()
        }
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            ViewModelQuick.get(this, NetCheckErrorPresenter::class.java)
                .onKeyDownEvent(keyCode, event)
            netCheckBackBtn.performClick()
        }
        return true
    }


    private fun setOnClickEvent() {
        netCheckBackBtn.setOnClickListener {
            if (netCheckBackBtn.isShown) {
                addLog("返回",0,"按下F1")
                finish()
            }
        }
        netCheckChargeBtn1.setOnClickListener {
            if (netCheckChargeBtn1.isShown) {
                checkDoubleClick()
            }
        }
        netCheckChargeBtn2.setOnClickListener {
            if (netCheckChargeBtn2.isShown) {
                checkDoubleClick()
            }
        }
        netCheckLookBtn.setOnClickListener {
            if (netCheckLookBtn.isShown) {
                addLog("进入雷管列表页",0,"按下F4")
                checkDelayCollector()
            }
        }
    }

    private fun checkDelayCollector() {
        DBHelper.queryLeiGuanEntity(object :
            ObservableUtil.Companion.OnNextCallback<List<LeiGuanEntity>>() {
            override fun onNext(t: List<LeiGuanEntity>) {
                DBHelper.queryLeiGuanDelayEntity(object :
                    ObservableUtil.Companion.OnNextCallback<List<LeiGuanDelayEntity>>() {
                    override fun onNext(delayData: List<LeiGuanDelayEntity>) {
                        ObservableUtil.doNext(ObservableOnSubscribe {
                            delayData.forEach { dd ->
                                t.forEach {
                                    if (TextUtils.equals(dd.UID, it.UID)) {
                                        dd.collectorNumber = it.collectorNumber
                                    }
                                }
                            }
                            it.onNext(delayData)
                        },
                            object :
                                ObservableUtil.Companion.OnNextCallback<List<LeiGuanDelayEntity>>() {
                                override fun onNext(t: List<LeiGuanDelayEntity>) {
                                    AppContext.appContext.setLeiGuanDelayEntity("netCheckDelay",t as ArrayList<LeiGuanDelayEntity>)
                                    val intent = Intent(
                                        this@NetCheckActivity,
                                        DetonatorListActivity::class.java
                                    )
                                    intent.putExtra("key", "netCheckDelay")
                                    startActivity(intent)
                                }
                            })
                    }
                })
            }
        })
    }


    @Synchronized
    private fun checkDoubleClick() {
        if (System.currentTimeMillis() - clickTime < 500) {
            addLog("进入爆破页",0,"同时按下充电起爆按钮")
            isBlastIntent = true
            val intent = Intent(this, BlastActivity::class.java)
            intent.putExtra("delay", true)

            if (!TextUtils.isEmpty(netCheckChargeText.text.toString())) {
                val replace = netCheckChargeText.text.toString().replace("电压:", "")
                val voltage = replace.replace("V", "").trim()
                intent.putExtra("voltage", voltage)
            }
            if (!TextUtils.isEmpty(netCheckElectricText.text.toString())) {
                val replace = netCheckChargeText.text.toString().replace("电流:", "")
                val electric = replace.replace("mA", "").trim()
                intent.putExtra("electric", electric)
            }
            clickTime = 0L
            startActivity(intent)
            finish()
        } else {
            if(clickTime != 0L) {
                clickTime  = 0L
                Toll.toll("同时按下充电起爆按钮")
            } else {
                clickTime = System.currentTimeMillis()
            }
        }
    }

    fun dismissButtonLayout() {
        netCheckBtnLayout.visibility = View.GONE
    }

    fun showOnlyBack() {
        netCheckBtnLayout.visibility = View.VISIBLE
        netCheckBackBtn.visibility = View.VISIBLE
        netCheckChargeBtn1.visibility = View.INVISIBLE
        netCheckChargeBtn2.visibility = View.INVISIBLE
        netCheckLookBtn.visibility = View.INVISIBLE
    }

    override fun onDestroy() {
        super.onDestroy()
        SerialPortManager.cancelIntervalWork()
        if(!isBlastIntent) {

           // SerialPortManager.close()
           // SerialPortManager.closePower()
        }
    }


    fun getTotal(): Int {
        return ViewModelQuick.get(this, NetCheckReadyPresenter::class.java).getTotal()
    }


    fun getVoltage(): Double {
        return ViewModelQuick.get(this, NetCheckChargePresenter::class.java).getVoltage()
    }


    fun getElectric(): Double {
        return ViewModelQuick.get(this, NetCheckChargePresenter::class.java).getElectric()
    }

    fun addLog(action: String, p: Int, remark: String) {
        LogEntity.addLog(
            action,
            "",
            "延时组网",
            getTotal(),
            getElectric(),
            getVoltage(),
            "",
            p,
            0,
            "",
            remark
        )
    }




}